package cController

import (
	"reflect"
	"sync"
)

type ControllerContainer struct {
	lock      sync.RWMutex
	instances map[string]any
}

func (i *ControllerContainer) Save(instance any) bool {
	i.lock.Lock()
	defer i.lock.Unlock()

	app, name := instance.(ControllerInterface).ControllerName()
	index := app + "." + name
	i.instances[index] = instance

	return true
}

func (i *ControllerContainer) Get(name string) any {
	i.lock.RLock()
	defer i.lock.RUnlock()

	return i.instances[name]
}

func (i *ControllerContainer) Remove(name string) bool {
	i.lock.Lock()
	defer i.lock.Unlock()

	delete(i.instances, name)

	return true
}

func (i *ControllerContainer) Is(instance any) bool {
	return reflect.TypeOf(instance).Implements(reflect.TypeOf((*ControllerInterface)(nil)).Elem())
}

func (i *ControllerContainer) Range(f func(instance any)) {
	i.lock.RLock()
	defer i.lock.RUnlock()

	for _, item := range i.instances {
		f(item)
	}
}

var container = &ControllerContainer{
	lock:      sync.RWMutex{},
	instances: make(map[string]any),
}
